<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>取消请求</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
  </head>

  <body>
    <!-- 
        xhr.abort()
     -->
    <button>发送请求</button>
    <button>取消请求</button>
    <script>
      let btns = document.querySelectorAll("button");
      //1. 声明一个外部变量
      let cancel = null;

      btns[0].onclick = async function () {
        try {
          // 2. 在配置对象中 配置 cancelToken 的值
          let result = await axios.get("http://127.0.0.1:8090/tes", {
            //
            cancelToken: new axios.CancelToken((c) => {
              //将 c 参数赋值给外部变量
              cancel = c;
            }),
          });
          console.log(result);
        } catch (e) {
          console.dir(e)
        }
      };

      btns[1].onclick = async function () {
        //判断
        if (typeof cancel !== "function") return;
        //3. 执行 cancel 函数
        cancel();
      };
    </script>
  </body>
</html>
